package com.cy.server.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 * @peoject: yeb
 * @description: 自定义Authority解析器
 * @author: LiShaoZhuo
 * @create: 2021-05-10 17:08
 **/
public class CustomAuthorityDeserializer extends JsonDeserializer {

    @Override
    public Object deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
        //获取ObjectMapper对象
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        List<GrantedAuthority> grantedAuthorityList = new LinkedList<>();
        //通过mapper对象读取树
        JsonNode jsonNode = mapper.readTree(jsonParser);
        //获取树节点上的元素
        Iterator<JsonNode> elements = jsonNode.elements();
        while (elements.hasNext()){
            JsonNode next = elements.next();
            //拿到authority里面的数据
            JsonNode authority = next.get("authority");
            grantedAuthorityList.add(new SimpleGrantedAuthority(authority.asText()));
        }
        return grantedAuthorityList;
    }
}
